/**
 * 包含应用中所有接口请求函数的模块
 * 每个函数的返回值都是promise
 */
import { message } from 'antd'
import jsonp from 'jsonp'
import ajax from './ajax'

/**
 * 登录
 * @param {*} username 
 * @param {*} password 
 */
export const reqLogin = (username, password) => ajax('/login', { username, password }, 'POST')

/**
 * 获取分类列表
 * @param {*} data 
 */
export const reqCatagoryList = (data) => ajax('/manage/category/list', data, 'GET')

/**
 * 添加分类
 * @param {*} data 
 */
export const reqAddCategory = (data) => ajax('/manage/category/add', data, 'POST')

/**
 * 更新分类
 * @param {*} data 
 */
export const reqUpdateCategory = (data) => ajax('/manage/category/update', data, 'POST')


/**
 * jsonp请求定位接口
 */
export const reqAddress = () => {
	return new Promise((resolve, reject) => {
		jsonp('https://api.map.baidu.com/location/ip?ak=PFlNd9vKhGalbukR6ZIlFKzKvFsutPWV', (err, data) => {
			if (!err && data.status === 0) {
				resolve(data.content)
			} else {
				message.error('请求定位接口失败')
			}
		})
	})
}

/**
 * jsonp请求天气接口
 */
export const reqWeather = (city) => {
	return new Promise((resolve, reject) => {
		const url = `https://api.map.baidu.com/telematics/v3/weather?location=${city}&output=json&ak=3p49MVra6urFRGOT9s8UBWr2`
		//发送jsonp请求
		jsonp(url, {}, (err, data) => {
			if (!err && data.status === 'success') {
				const { dayPictureUrl, weather } = data.results[0].weather_data[2]
				resolve({ dayPictureUrl, weather })
			} else {
				message.error('获取天气信息失败')
			}
		})
	})
}
